package ds.linklist.simple;

/**链表的头结点*/
public class LinkList {

	private Link first = null; // 这个null后来一直往后传啊传~~
	// -----------------------------
	public boolean isEmpty(){
		return (first == null);
	}
	
	public void insertFirst(int i){
		Link newLink = new Link(i);
		newLink.next = first; // newLink -->(链接) old first
		first = newLink; // first ---> newLink
	}
	
	public Link deleteFirst()
	{
		if(!isEmpty())
		{
			Link temp = first;
			first = first.next;
			return temp;
		}
		else
		{
			return null;
		}
	}
	
	public Link find(int key)
	{
		Link current = first;
		while(current!=null)
		{
			if(current.getData() == key)
				return current;
			else
				current=current.next;
		}
		return null;
	}
	
	public Link delete(int key)
	{		
		Link previous = null;
		Link current = first;
		
		while(current != null)
		{
			if(current.getData() == key)
			{
				Link temp = current;
				if(current == first)
					first = current.next;
				else
				{
					previous.next = current.next;
					current.next = null;
				}
				return temp;
			}
			else
			{
				previous = current;
				current = current.next;
			}
		}
		return null;
	}
	
	public void displayList()
	{
		System.out.println("(first --> last):");
		Link current = first;
		while(current!=null)
		{
			current.displayLink();
			current = current.next;
		}
	}
	
	public Link getFirst()
	{
		return first;
	}
}

class LinkListApp{
	public static void main(String[] args)
	{
		LinkList ll = new LinkList();
		ll.insertFirst(1);
		ll.insertFirst(2);
		ll.insertFirst(3);
		ll.insertFirst(4);
		ll.insertFirst(5);
		ll.insertFirst(6);
		
		ll.displayList();
		
		ll.find(6).displayLink();
		ll.delete(7);
		ll.delete(6);
		ll.delete(4);
		ll.displayList();
		
//		自杀型代码：
//		int i=0;
//		while(true)
//		{
//			if(i%10000 == 0)
//			{
//				System.out.println(i);
//			}
//			ll.insertFirst(i++);
//			i++;
//		}
	}
}
